// 引入axios
import axios from "axios";
import { useStore } from "@/store"; //引入登录状态管理器
import crypto from "@/utils/crypto.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import router from "@/router";
// 请求超时时间
axios.defaults.timeout = 5000;
// 给 axios 设置请求根路径
// axios.defaults.baseURL = '/activity';
axios.defaults.baseURL = "/blog_admin" || "";
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // 这里的api就是获取configJS中的地址
  baseURL: "/blog_admin",
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const reqIv = import.meta.env.VITE_APP_IV;
const reqKey = import.meta.env.VITE_APP_KEY;

axios.create(config);

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    //是否存在token  需验证登录的请求
    const store = useStore();
    // 	config.headers['Content-Type'] = 'application/json;charset=utf-8';
    // 	config.headers['Access-Control-Allow-Origin'] = '*';
    // application/x-www-form-urlencoded 或 multipart/form-data
    if (store.token) {
      config.headers["Authorization"] = store.token;
    }
    return config;
  },
  (error) => {
    return Promise.error(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    const store = useStore();
    //200 通过则
    if (response.status === 200) {
      return Promise.resolve(response);
    } else if (response.status === 202) {
      //token失效时或者用户不存在时
      // console.log(router);
      store.setLogout(); //清除用户信息
      router.replace("/login"); //返回登录页
      return true;
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
          // console.log(500,"4");
          ElMessage.error("网错错误，请稍后再试！");
          break;
        case 404:
          ElMessage.error("网错错误，请稍后再试！");
          break;
        // case 202:
        //   console.log(55);
        //   break;
        // // 其他错误，直接抛出错误提示
        default:
          ElMessage.error(error.response.data.msg);
      }
      return true;
      //   return Promise.reject(error.response);
    }
  }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const get = (url, params = {}, token = "") => {
  if (token != "") {
    axios.defaults.headers.common["X-CSRF-TOKEN"] = token;
  }
  let param = {};
  //参数不为空，加密
  if (Object.keys(params).length > 0) {
    const nowtime = parseInt(new Date().getTime() / 1000) + "";
    param.time = nowtime;
    params = JSON.stringify(params); //对象转为字符串
    param.key = crypto.encrypt(params, nowtime + reqKey, reqIv);
  }
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: param,
      })
      .then((res) => {
        let result = res.data;
        //不为空时则是需要解密
        if (result.data.key != '') {
          result.data = crypto.decrypt(
            result.data.key,
            result.data.time + reqKey,
            reqIv
          ); //解密
        }
        resolve(result); //执行
      })
      .catch((err) => {
        // ElMessage.error(err.data.msg);
        reject(err.data);
      });
  });
};
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const post = (url, params = {}, token = "") => {
  if (token != "") {
    axios.defaults.headers.common["X-CSRF-TOKEN"] = token;
  }
  //参数不为空，加密
  let param = {};
  //参数不为空，加密
  if (Object.keys(params).length > 0) {
    const nowtime = parseInt(new Date().getTime() / 1000) + "";
    param.time = nowtime;
    params = JSON.stringify(params); //对象转为字符串
    param.key = crypto.encrypt(params, nowtime + reqKey, reqIv);
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, param)
      .then((res) => {
        let result = res.data;
        //不为空时则是需要解密
        if (result.data.key != '') {
          result.data = crypto.decrypt(
            result.data.key,
            result.data.time + reqKey,
            reqIv
          ); //
        }
        resolve(result); //执行
      })
      .catch((err) => {
        // ElMessage.error(err.data.msg);
        reject(err.data);
      });
  });
};

/**
 * post方法，文件上传 参数不需要加密
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const file_post = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        let result = res.data;
        result.data = crypto.decrypt(
          result.data.key,
          result.data.time + reqKey,
          reqIv
        ); //解密
        resolve(result); //执行
      })
      .catch((err) => {
        // ElMessage.error(err.data.msg);
        reject(err.data);
      });
  });
};

//end

var api = {
  get,
  post,
  file_post,
};
export default api;
